<?php

namespace App\Http\Controllers\Api;

use EasyWeChat\Factory;
use App\Http\Controllers\Controller as BaseController;
use App\Models\Tenant;
use EasyWeChat\Kernel\Support\XML;
use Illuminate\Http\Request;

class Controller extends BaseController
{
    protected $tenant = null;
    protected $mini_program = null;
    protected $mini_payment = null;

    public function __construct()
    {
        $header_signid = request()->header('signid');
//        dd(md5('wx7a1f6cd22d73f2a4'));
        $tenant = Tenant::where(['md5_weapp_id' => $header_signid])->first();
        if (!$tenant) {
            return api()->failed('此商户尚未开通服务');
        }
        $this->tenant = $tenant;
        $mini_program_config = [
            'app_id' => $tenant->weapp_id,
            'secret' => $tenant->weapp_secret,
        ];
        $this->mini_program = Factory::miniProgram($mini_program_config);
        $mini_payment_config = [
            'app_id' => $tenant->weapp_id,
            'mch_id' => $tenant->mch_id,
            'key' => $tenant->mch_key,
        ];
        $this->mini_payment = Factory::payment($mini_payment_config);
    }

    protected function getNotify(Request $request = null)
    {
        $request = Request::createFromGlobals();
        try {
            $xml = XML::parse(strval($request->getContent()));
        } catch (\Throwable $e) {
            throw new \Exception('Invalid request XML: ' . $e->getMessage(), 400);
        }

        if (!is_array($xml) || empty($xml)) {
            throw new \Exception('Invalid request XML.', 400);
        }
        return $xml;
//        \Log::channel('pay_notify')->info("微信支付回调数组：" . json_encode($xml));
//        return new Collection($xml);
    }
}
